package com.fitness.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;



public class FileUtil {
	/**
	 * @param file springmvc接受的文件 指定目录
	 * @param request httpservletRequest
	 */
	public static Map<String,String> savePicture(MultipartFile file,String dest,HttpServletRequest request){
		File dir = new File(dest);
		if(!dir.exists()){
			dir.mkdirs();
		}
		System.out.println();
		String[] flush = file.getOriginalFilename().split("\\.");
		String  suffix = flush[flush.length-1];
		String fileName = UUID.randomUUID().toString();//随机的uuid
		String  path = dir.getPath()+"/"+fileName+"."+suffix;
		try {
			file.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String,String> map =  new HashMap<String,String>();
		map.put("path",path);
		map.put("url", fileName+"."+suffix);
		map.put("suffix",suffix);
		map.put("fileName", fileName);
		return map;
	}
	/**
	 * 上传多个文件 
	 */
	public static Map<String, String> saveFiles(List<MultipartFile> files,HttpServletRequest request){
		String dest="E:/carehome_file/resource/picture";
		Map<String, String> result = new HashMap<>();
		int i=1;
		for(MultipartFile file:files){
			Map<String, String> map =  FileUtil.savePicture(file, dest, request);
			result.put("file"+i,"/resource/picture/"+map.get("url"));
			i++;
		}
		result.put("count", i+"");//统计数
		return result;
	}
	
	/**保存文件
     * @param stream
     * @param path
     * @param filename
     * @throws IOException
     */
    public static void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
    {      
        FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0; 
        while ((byteread=stream.read(buffer))!=-1)
        {
           bytesum+=byteread;
           fs.write(buffer,0,byteread);
           fs.flush();
        } 
        fs.close();
        stream.close();      
    }       
}


	